import { defineStore } from 'pinia'
import { ref, computed } from 'vue'
import i18n from '../locales'

export type Language = 'en' | 'es' | 'ja'

export const useLanguageStore = defineStore('language', () => {
  // 当前语言
  const currentLanguage = ref<Language>('en')
  
  // 语言列表
  const languages = ref([
    { code: 'en', name: 'English', flag: '🇺🇸' },
    { code: 'es', name: 'Español', flag: '🇪🇸' },
    { code: 'ja', name: '日本語', flag: '🇯🇵' }
  ])
  
  // 当前语言对象
  const currentLanguageInfo = computed(() => {
    return languages.value.find(lang => lang.code === currentLanguage.value)
  })
  
  // 切换语言
  const setLanguage = (lang: Language) => {
    currentLanguage.value = lang
    i18n.global.locale.value = lang
    // 保存到localStorage
    localStorage.setItem('language', lang)
  }
  
  // 初始化语言
  const initLanguage = () => {
    const savedLanguage = localStorage.getItem('language') as Language
    if (savedLanguage && languages.value.some(lang => lang.code === savedLanguage)) {
      setLanguage(savedLanguage)
    } else {
      // 根据浏览器语言自动选择
      const browserLang = navigator.language.toLowerCase()
      if (browserLang.includes('es')) {
        setLanguage('es')
      } else if (browserLang.includes('ja')) {
        setLanguage('ja')
      } else {
        setLanguage('en')
      }
    }
  }
  
  return {
    currentLanguage,
    languages,
    currentLanguageInfo,
    setLanguage,
    initLanguage
  }
})